<template>
  <div id="tableConfig">
    <div class="columnsInfo">
      <h4>{{$t('config.columnsInfo')}}</h4>
      <el-form 
        :model="routeData"
        :rules="rules"
        ref="ruleForm"
        :inline="true"
        label-width="100px"
        class="demo-ruleForm"
       
      >
        <el-form-item :label="$t('config.menuName')" prop="menu_id" class="base-width-25">
          <el-select
            v-model="routeData.menu_id"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteMethod"
            @change="selected"
          >
            <el-option
              v-for="(item, i) in menuList"
              :key="i"
              :label="item.menu_name"
              :value="item.menu_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('config.menuCode')" prop="menu_code" class="base-width-25">
          <el-input v-model="routeData.menu_code" disabled></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('config.listName')"
          prop="menu_list_name"
          class="base-width-25"
        >
          <el-input v-model="routeData.menu_list_name"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('config.listCode')"
          prop="menu_list_code"
          class="base-width-25"
        >
          <el-input v-model="routeData.menu_list_code"></el-input>
        </el-form-item>
        <el-form-item :label="$t('app.remark')" prop="remark" class="base-width-75">
          <el-input v-model="routeData.remark"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('config.searchSql')"
          prop="sql_text"
          class="base-width-100"
        >
          <el-input type="textarea" v-model="routeData.sql_text"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('config.countSql')"
          prop="total_sql_text"
          class="base-width-100"
        >
          <el-input
            type="textarea"
            v-model="routeData.total_sql_text"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>

    <div class="columnsSetting">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane :label="$t('config.listInfo')" name="first">
          <ag-grid
            class="no-edit no-check"
            :searchBox="false"
            v-model="gridObjInfo"
            :defaultColDef="defaultColDefInfo"
            rowSelection="single"
            :highlightCurrentRow="true"
            :rowDragManaged="true"
            :disabled="true"
            :hasAction="true"
            :data.sync="rowDataInfo"
            :height.sync="heightInfo"
            :tmsShowFilter="false"
            :columnConfig='{menu_id: "gridColumnsInfo", menu_code:"gridColumnsInfo", menu_list_code:"gridColumnsInfo"}'
            :enterMovesDown="true"
            :enterMovesDownAfterEdit="true"
            :showSummary="false"
            :pageDetail="false"
            :tableSettingVisible.sync="showTableSettingInfo"
            @selection-change="handleSelectionChangeInfo"
            @action="handleAction"
            @grid-ready="agGridReadyInfo"
          >
          </ag-grid>
        </el-tab-pane>
        <el-tab-pane :label="$t('config.listSort')" name="second">
          <ag-grid
            class="no-edit no-check"
            rowSelection="single"
            :searchBox="false"
            v-model="gridObjSort"
            :rowDragManaged="true"
            :defaultColDef="defaultColDefSort"
            :highlightCurrentRow="true"
            :disabled="true"
            :hasAction="true"
            :data.sync="rowDataSort"
            :height.sync="heightSort"
            :tmsShowFilter="false"
            :columnConfig='{menu_id: "gridColumnsSort", menu_code:"gridColumnsSort", menu_list_code:"gridColumnsSort"}'
            :showSummary="false"
            :enterMovesDown="true"
            :enterMovesDownAfterEdit="true"
            :pageDetail="false"
            :tableSettingVisible.sync="showTableSettingSort"
            @action="handleAction"
            @selection-change="handleSelectionChangeSort"
            @grid-ready="agGridReadySort"
          >
          </ag-grid>
        </el-tab-pane>
      </el-tabs>
      <div class="btns">
        <el-button type="primary" @click="save">{{$t("common.save")}}</el-button>
        <el-button @click="cancel">{{$t("common.cancel")}}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import agGrid from "commons/AgGrid/index.vue";
import {
  querySysColumnDefineById,
  queryMenuListByName,
  updateSysColumnDefine,
  saveSysColumnDefine,
} from "@/api/system/table.js";
export default {
  name: "tableConfig",
  data() {
    return {
      activeName: "first",
      heightInfo: 0,
      heightSort: 0,
      routeData: {
        menu_code: "",
        menu_list_code: "",
        menu_list_name: "",
        menu_id: "",
        sql_text: "",
        total_sql_text: "",
      },
      rules: {
        menu_code: [
          { required: true, message: "请选择菜单名称", trigger: "change" },
        ],
        menu_id: [
          { required: true, message: "请选择菜单名称", trigger: "blur" },
        ],
        menu_list_code: [
          { required: true, message: "请输入列表编码", trigger: "blur" },
        ],
        menu_list_name: [
          { required: true, message: "请输入列表名称", trigger: "blur" },
        ],
      },
      defaultColDefInfo: {
        editable(param) {
          return param.colDef.editable;
        },
        sortable: false,
        filter: false,
      },
      defaultColDefSort: {
        editable(param) {
          return param.colDef.editable;
        },
        sortable: false,
        filter: false,
      },
      gridObjInfo: {},
      gridObjSort: {},
      rowDataInfo: [
        {
          sort_num: "",
          code: "",
          name: "",
          issearch: "",
          type: "",
          width: "50",
        },
      ],
      rowDataSort: [
        { sort_num: "", sort_type: "", column_code: "", menu_list_name: "" },
      ],
      showTableSettingInfo: false,
      showTableSettingSort: false,
      infoObj: {
        sort_num: "",
        code: "",
        name: "",
        issearch: "",
        type: "",
        width: 50,
      },
      sortObj: {
        sort_num: "",
        sort_type: 10202,
        column_code: "",
        menu_list_name: "",
      },
      newFlag: false,
      menuList: [],
    };
  },
  components: {
    agGrid,
  },
  mounted() {
    if (this.$store.state.routeData) {
      this.routeData = this.$store.state.routeData;
      this.getDetails(this.routeData.id);
    }
    this.heightInfo = this.getHeight(window, 250);
    this.heightSort = this.getHeight(window, 250);
  },
  methods: {
    addAction() {
      if (this.hasAction) {
        let indexCloumn = {
          headerName: "操作",
          field: "action",
          minWidth: 50,
          width: 50,
          cellRenderer: "ActionRender",
          cellClass: "tms-cell-action",
          headerClass: "tms-no-children-header",
        };
        this.columns.push(indexCloumn);
      }
      console.log(this.columns);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    agGridReadySort(params) {
      this.gridObjSort = params;
    },
    agGridReadyInfo(params) {
      this.gridObjInfo = params;
    },
    getDetails(id) {
      querySysColumnDefineById(id).then((res) => {
          this.menuList.push({
            menu_name: res.bean.menu_name,
            menu_id: res.bean.menu_id,
          });
          this.rowDataInfo = res.bean.sysColumnDefineDetailList;
          this.rowDataSort = res.bean.sysColumnDefineSortList;
          if (this.rowDataInfo.length == 0) {
            this.rowDataInfo = [this.infoObj];
            this.gridObjInfo.api.setRowData(this.rowDataInfo);
          }
          if (this.rowDataSort.length == 0) {
            this.rowDataSort = [this.sortObj];
            this.gridObjSort.api.setRowData(this.rowDataSort);
          }
        
      });
    },
    handleCurrentChangeSort() {},
    handleAction(index, type) {
      if (type == "delete") {
        if (this.rowDataInfo.length > 1) {
          if (this.activeName == "first") {
            this.rowDataInfo.splice(index, 1);
            this.gridObjInfo.api.setRowData(this.rowDataInfo);
          } else {
            this.rowDataSort.splice(index, 1);
            this.gridObjSort.api.setRowData(this.rowDataSort);
          }
        }
      } else if (type == "add") {
        this.reset();
        if (this.activeName == "first") {
          this.rowDataInfo.splice(index, 0, this.infoObj);
        } else {
          this.rowDataSort.splice(index, 0, this.sortObj);
        }
      }
    },
    add(type) {
      if (type === "info") {
        if (
          this.infoObj.code != "" &&
          this.infoObj.name != "" &&
          this.infoObj.issearch != "" &&
          this.infoObj.type != "" &&
          this.infoObj.width != ""
        ) {
          // 如果此时下方表格内容不为空 则判断是修改还是新增
          if (this.rowDataInfo.length > 0) {
            let flag = false;
            let i = null;
            this.rowDataInfo.forEach((item, index) => {
              if (this.infoObj.code === item.code) {
                flag = true;
                i = index;
              }
            });
            if (flag) {
              var rowNode = this.gridObjInfo.api.getRowNode(i); //获取表格第i行数据
              //更新数据
              rowNode.setData(this.infoObj);
            } else {
              this.rowDataInfo.push(this.infoObj);
            }
          } else {
            this.rowDataInfo.push(this.infoObj);
          }
          this.reset();
        } else {
          this.$message.error(this.$t('msg.msg15'));
        }
      } else {
        if (
          this.sortObj.column_code != "" &&
          this.sortObj.menu_list_name != "" &&
          this.sortObj.sort_type != ""
        ) {
          // 如果此时下方表格内容不为空 则判断是修改还是新增
          if (this.rowDataSort.length > 0) {
            let flag = false;
            let i = null;
            this.rowDataSort.forEach((item, index) => {
              if (this.sortObj.column_code === item.column_code) {
                flag = true;
                i = index;
              }
            });
            if (flag) {
              var rowNode = this.gridObjSort.api.getRowNode(i); //获取表格第i行数据
              //更新数据
              rowNode.setData(this.sortObj);
            } else {
              this.rowDataSort.push(this.sortObj);
            }
          } else {
            this.rowDataSort.push(this.sortObj);
          }
          this.reset();
        } else {
          this.$message.error(this.$t('msg.msg15'));
        }
      }
    },
    del(type) {
      if (type === "info") {
        // var selRows = this.gridObjInfo.api.getSelectedRows(); //获取选中的行
        // this.gridObjInfo.api.updateRowData({ remove: selRows });
        if (
          this.infoObj.sort_num != "" &&
          this.infoObj.code != "" &&
          this.infoObj.name != "" &&
          this.infoObj.issearch != "" &&
          this.infoObj.type != "" &&
          this.infoObj.width != ""
        ) {
          // 如果此时下方表格内容不为空 则判断是修改还是新增
          if (this.rowDataInfo.length > 0) {
            let flag = false;
            let i = null;
            this.rowDataInfo.forEach((item, index) => {
              if (this.infoObj.code === item.code) {
                flag = true;
                i = index;
              }
            });
            if (flag) {
              this.rowDataInfo.splice(i, 1);
            }
          }
          this.reset();
        } else {
          this.$message.error(this.$t('msg.msg16'));
        }
      } else {
        // var selRows = this.gridObjSort.api.getSelectedRows();
        // this.gridObjSort.api.updateRowData({ remove: selRows });
        if (
          this.sortObj.sort_num != "" &&
          this.sortObj.column_code != "" &&
          this.sortObj.menu_list_name != "" &&
          this.sortObj.sort_type != ""
        ) {
          // 如果此时下方表格内容不为空 则判断是修改还是新增
          if (this.rowDataSort.length > 0) {
            let flag = false;
            let i = null;
            this.rowDataSort.forEach((item, index) => {
              if (this.sortObj.code === item.code) {
                flag = true;
                i = index;
              }
            });
            if (flag) {
              this.rowDataSort.splice(i, 1);
            }
          }
          this.reset();
        } else {
          this.$message.error(this.$t('msg.msg16'));
        }
      }
      this.reset();
    },
    reset() {
      this.infoObj = {
        sort_num: "",
        prop: "",
        name: "",
        issearch: "",
        type: "",
        width: "",
      };
      this.sortObj = {
        sort_num: "",
        sort_type: "",
        column_code: "",
        menu_list_name: "",
      };
    },
    save() {
      this.gridObjInfo.api.stopEditing();
      let arrInfo = [];
      let arrSort = [];
      this.gridObjInfo.api.forEachNode(function(node, index) {
        node.data.sort_num = index + 1;
        arrInfo.push(node.data);
      });
      this.gridObjSort.api.forEachNode(function(node, index) {
        node.data.sort_num = index + 1;
        arrSort.push(node.data);
      });
      console.log(arrInfo, "arrInfo", arrSort, "arrSort");
      let data = {};
      data = this.routeData;
      data.sysColumnDefineDetailList = arrInfo;
      data.sysColumnDefineSortList = arrSort;
      const infoValidate = this.tableValidate(arrInfo, [
        "code",
        "name",
        "issearch",
        "type",
        "width",
      ]);
      const sortValidate = this.tableValidate(arrSort, [
        "column_code",
        "menu_list_name",
        "sort_type",
      ]);

      if (infoValidate && sortValidate) {
        if (!this.routeData?.id) {
          data.column_config_type = 10001;
          saveSysColumnDefine(data).then((res) => {
              this.$message.success(this.$t('app.saveMes'));
              this.cancel();
          });
        } else {
          updateSysColumnDefine(data).then((res) => {
              this.$message.success(this.$t('app.saveMes'));
              this.cancel();
          });
        }
      }
    },
    tableValidate(data, keys) {
      let indexArr = [];
      data.forEach((item, index) => {
        keys.forEach((key) => {
          if (item[key] == "") {
            console.log(key);
            indexArr.push(index);
          }
        });
      });
      indexArr = [...new Set(indexArr)];
      if (indexArr.length > 0) {
        const gridApi =
          this.activeName == "first" ? this.gridObjInfo : this.gridObjSort;
        gridApi.api.forEachNode(function(node) {
          node.setSelected(node.rowIndex === indexArr[0]);
        });
        this.$message.error(this.$t('msg.msg15'));
        return false;
      }
      return true;
    },
    cancel() {
      this.$router.push({ name: "tableConfigList" });
    },
    remoteMethod(string) {
      if (string !== "") {
        this.menuList = [];
        queryMenuListByName(string).then((res) => {
            this.menuList = this.menuList.concat(res.list);
          
        });
      }
    },
    selected(item) {
      this.routeData.menu_code = this.menuList.filter((i) => {
        return i.menu_id === item;
      })[0].menu_code;
      this.routeData.menu_name = this.menuList.filter((i) => {
        return i.menu_id === item;
      })[0].menu_name;
      this.routeData.menu_id = this.menuList.filter((i) => {
        return i.menu_id === item;
      })[0].menu_id;
    },
    handleSelectionChangeInfo(data) {
      if (data.length === 0) {
        this.reset();
        return;
      }
      this.infoObj = data[0];
    },
    handleSelectionChangeSort(data) {
      if (data.length === 0) {
        this.reset();
        return;
      }
      this.sortObj = data[0];
    },
  },
};
</script>

<style lang="scss" scoped>
#tableConfig {
  overflow: hidden;
  ::v-deep .el-tabs__item {
    padding: 0 8px !important;
  }

  .columnsSetting {
    width: 100%;
    overflow: hidden;
    ::v-deep .el-input__inner {
      height: 28px;
      line-height: 28px;
      border: 0;
      border-radius: 0;
    }
    .inputs-info {
      width: 100%;
      position: relative;
      margin-bottom: 8px;

      .prop {
        width: 15%;
        margin-left: 2%;
        display: inline-block;
      }

      .name {
        width: 15%;
        margin-left: 5%;
        display: inline-block;
      }

      .query {
        width: 15%;
        margin-left: 5%;
        display: inline-block;
      }

      .type {
        width: 15%;
        margin-left: 4%;
        display: inline-block;
      }

      .width {
        width: 80px;
        margin-left: 4%;
        display: inline-block;
      }

      .sortType {
        width: 200px;
        display: inline-block;
      }

      .add {
        position: absolute;
        right: 48px;
        top: 0;
      }

      .del {
        position: absolute;
        right: 0px;
        top: 0;
      }

      .el-button {
        width: 40px;
        margin-left: 8px;
      }
    }

    .inputs-sort {
      width: 100%;
      position: relative;
      margin-bottom: 8px;

      .prop {
        width: 15%;
        margin-left: 4%;
        display: inline-block;
      }

      .name {
        width: 15%;
        margin-left: 16%;
        display: inline-block;
      }

      .sortType {
        width: 120px;
        margin-left: 16%;
        display: inline-block;
      }

      .add {
        position: absolute;
        right: 48px;
        top: 0;
      }

      .del {
        position: absolute;
        right: 0px;
        top: 0;
      }

      .el-button {
        width: 40px;
        margin-left: 8px;
      }
    }
  }

  .btns {
    width: 100%;
    text-align: center;
    margin-top: 16px;
  }

  .demo-ruleForm {
    .el-select {
      height: 25px;

      ::v-deep .el-input {
        height: 25px;
      }
    }
  }
}
</style>
